package com.lagou.config;

import com.lagou.mapping.SqlCommandType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");
        if(selectList != null && selectList.size() > 0){
            packageElementToMapperStatement(selectList, namespace, SqlCommandType.SELECT);
        }

        List updateList = rootElement.selectNodes("//update");
        if(updateList != null && updateList.size() > 0){
            packageElementToMapperStatement(updateList, namespace, SqlCommandType.UPDATE);
        }

        List deleteList = rootElement.selectNodes("//delete");
        if(deleteList != null && deleteList.size() > 0){
            packageElementToMapperStatement(deleteList, namespace, SqlCommandType.DELETE);
        }

    }

    private void packageElementToMapperStatement(List<Element> list, String namespace, SqlCommandType type){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParamterType(paramterType);
            mapperStatement.setSql(sql);
            mapperStatement.setSqlCommandType(type);
            configuration.getMapperStatementMap().put(namespace+"."+id, mapperStatement);
        }
    }

}
